<?php

namespace App\Http\Controllers\Company\Auth;
use App\Facades\Style;
use App\Models\Company\CompanyUser;
use App\Http\Requests\Personal\Login\AjaxLoginRequest;
use App\Http\Requests\Company\Login\AjaxCompanyLoginRequest;
use Illuminate\Http\Request;
use App\Models\Company\CompanyLoginRecord;
use App\Models\Company\CompanyVisitRecord;
use App\Models\Personal\PersonalUser;
use Jenssegers\Agent\Facades\Agent;
use App\Http\Controllers\Controller;
use Auth,Site;
use Illuminate\Support\Facades\Session;
define('__QQAPITYPE__','company');
require_once('../app/Vendor/QqConnect/API/qqConnectAPI.php');
class QQLoginController extends Controller{

    /**
     * 企业QQ登录
     */
    public function companyQQLogin(){
        $qc = new \QC();
        $qc->qq_login();
    }

    /**
     * QQ 返回企业值
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function companyQQConnect(){
        if(Agent::isMobile() || Agent::isTablet()){
            $isMobile = 1;//手机登录
        }else{
            $isMobile = 0;//网站登录
        }
        $user = auth()->guard('company')->user();
        //返回地址
        $qc = new \QC();
        $token = $qc->qq_callback();
        $openId = $qc->get_openid();
        $unionId = $qc->get_unionid();
        $qc = new \QC($token,$openId);
        $userInfo = $qc->get_user_info();
        $userImg = $userInfo['figureurl_2'];
        $usname=$userInfo["nickname"];//名字
        //查找个人库里是否已存在
        $CompanyUser = CompanyUser::where('qqopenid',$openId)
            ->orWhere(function ($query) use ($unionId) {
                if(!empty($unionId)){
                    $query->where('qqunionid', $unionId);
                }
             })
            ->first();
        if($CompanyUser){//已注册过
            Auth::guard('company')->login($CompanyUser);
            $user = auth()->guard('company')->user();
            if(empty($user->qqunionid) && !empty($unionId)){//如之前没有unionid现已开启unionid当存入
                $user->qqopenid =$openId;
                $user->qqunionid =$unionId;
                $user->save();
            }
            //登录记录表
            $this->loginRecord($user,$isMobile);
            //更新用户表
            $this->updateUser($user);

            return redirect("/");
        }elseif(!empty($user->uid)) {
            $user->qqopenid =$openId;
            $user->qqunionid =$unionId;
            $user->save();
            return redirect("company/set_account");
        }else{
            //查询companyLogin 是否等1，等于1直接登录
            switch(Site::get('companyLogin')){
                case 0:
                    Session::put('openId', $openId);
                    Session::put('unionId', $unionId);
                    Session::put('userImg', $userImg);
                    Session::put('usname', $usname);

                    if($isMobile == 1){
                        return redirect('mobile/company/qqbinding?openid='.$openId);
                    }else{
                        return redirect('company/qqbinding');
                    }
                    break;
                case 1:
                    if(!empty($openId)){
                        $rename = $this->rename($usname);
                        $create = [
                            'username' => $rename,
                            'password' => str_random(60),
                            'mobile' => '',
                            'contacts' => '',
                            'company_name' => '',
                            'email' => '',
                            'regip' => getIp(),
                            'phone' => '',
                            'qqopenid' => $openId,
                            'qqunionid' => $unionId?$unionId:null,
                            'last_login_ip' => getIp(),
                            'regtime' => date('Y-m-d H:i:s',time()),
                            'updatetime' => date('Y-m-d H:i:s',time()),
                            'last_login_time' => date('Y-m-d H:i:s',time()),
                            'surpris_visit_time' => date('Y-m-d H:i:s',time())
                        ];
                        if($newUser = CompanyUser::create($create)){
                            Auth::guard('company')->login($newUser);
                            $user = auth()->guard('company')->user();
                            //登录记录表
                            $this->loginRecord($user,$isMobile);
                            return redirect("/");
                        }else{
                            return redirect('company/qqlogin');
                        }
                    }
                break;
            }
        }
    }

    /**
     * 自动登录，重命名用户名
     * @param $usname
     * @return string
     */
    
    protected function rename($usname){
        $CompanyUser = CompanyUser::select('username')->where('username',$usname)->first();
        if($CompanyUser){
            $reusname = $usname.'_'.str_random(8);
            return $this->rename($reusname);
        }else{
            return $usname;
        }
    }
    /**
     * QQ绑定现有企业账号
     * @param AjaxLoginRequest $request
     */
    public function companyQQBinDing(){
        $userImg = session('userImg');
        $usname = session('usname');
        //Session::forget('usname');
        if(Session::has('openId')){
            return Style::view("company.auth.binDingRegister",compact('userImg','usname'));
        }else{
            return redirect('company/qqlogin');
        }
    }

    /**
     * QQ绑定新注册企业
     */
    public function companyNewQQBinDing(){
        if(Session::has('openId')){
            $openId = session('openId');
            //ession::forget('openId');
            //Session::forget('userImg');
            return Style::view("company.auth.newBinDingRegister",compact('openId'));
        }else{
            //Session::forget('openId');
            //Session::forget('userImg');
            return redirect('company/qqlogin');
        }
    }
    /**
     * 保存企业QQ绑定
     * @param AjaxCompanyLoginRequest $request
     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function stroyCompanyQQBinDing(AjaxCompanyLoginRequest $request){
        $request->only('username','password');
        $request->flash();
        if(Auth::guard('company')->attempt(['username' => $request->username, 'password' => $request->password])
            or Auth::guard('company')->attempt(['mobile' => $request->username, 'password' => $request->password])){
            $user = Auth::guard('company')->user();
            if(!Session::has('openId')){
                return redirect('company/qqlogin');
            }
            if(CompanyUser::where('uid',$user->uid)->update(['qqopenid'=>session('openId'),
                'qqunionid'=>session('unionId')?session('unionId'):null])){
                Session::forget('openId');
                Session::forget('unionId');
                Session::forget('userImg');
                Session::forget('usname');
                //登录记录表
                $this->loginRecord($user,0);
                return redirect('company/jobadmin');
            }else{
                return back()->withErrors(['handleErr'=>'绑定失败，请稍候再试！']);
            }
        }else{
            return back()->withErrors(['handleErr'=>'密码错误！']);
        }
    }


    /**
     * 登录记录信息
     * @param $userInfo
     */
    public function loginRecord($userInfo,$isMobile){
        //登录记录表
        $record = array();
        $record['uid'] = $userInfo->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s',time());
        if($isMobile == 1){
            $record['login_type'] = 4;
        }else{
            $record['login_type'] = 2;
        }
        $record['type'] = 2;
        //登录记录表
        CompanyLoginRecord::create($record);

        //更新用户表
        $currtime = date('Y-m-d H:i:s',time());
        $fifedate = date('Y-m-d H:i:s',strtotime($userInfo->surpris_visit_time . "+15 day"));
        if($fifedate < $currtime ){
            $userInfo->surpris_visit_time = date('Y-m-d H:i:s',time());
            //15天内插入突访记录表
            CompanyVisitRecord::create($record);
        }
        $userInfo->last_login_time = date('Y-m-d H:i:s',time());
        $userInfo->last_login_ip = getIp();
        $userInfo->save();
    }

    /**
     * 更新用户表记录
     * @param $userInfo
     */
    public function updateUser($userInfo){
        //合并到登录记录信息
        //更新用户表
        /*$currtime = date('Y-m-d H:i:s',time());
        $fifedate = date('Y-m-d H:i:s',strtotime($userInfo->surpris_visit_time . "+15 day"));
        if($fifedate < $currtime ){
            $userInfo->surpris_visit_time = date('Y-m-d H:i:s',time());
        }
        $userInfo->last_login_time = date('Y-m-d H:i:s',time());
        $userInfo->last_login_ip = getIp();
        $userInfo->save();*/
    }

}